const url           = require('url');
const async         = require('async');
const BaseHandler   = require('../base-handler');
const SystemServices = require('../../../constants').SystemServices;
const HTTP_VERBS = require('../../../constants').HTTP_VERBS;

class ConsoleHandler extends BaseHandler {

    get pattern() {
        return "/console";
    }

    doGET(request, response) {
        if(!request.session.user.authenticated) {
            response.redirect('/login')
        } else {
            /*response.render('console/home', {
                user: request.session.user,
                data: [],
                plan: {}
            });*/

            var referer = request.headers['referer'];
            var hasReferer = !!referer;
            
            var source = request.query.from || undefined || request.session.user.from;
            if (hasReferer) {
                referer = url.parse(referer).path
            }

            if (!request.query.from && !hasReferer || (hasReferer && ['login', 'signup'].indexOf(referer) >= 0)) {
                source = undefined;
            }

            request.session.user.from = source;

            var userId = request.session.user.id;
            var me = this;
            async.waterfall([
                (callback) => {
                    me.Controller.getWallsByUserId(userId, (walls) => {
                        callback(null, walls);
                    });
                },
                (walls, callback) => {
                    if (walls.length > 0) {
                        callback(null);
                    } else {
                        response.redirect("/get-started");
                    }
                },
                () => {
                    me.Controller.getPlanInfo(userId, (result) => {
                        if(result.success) {
                            request.session.user.plan_id = result.data.id;
                            response.render('console/home', {
                                user: request.session.user,
                                data: [],
                                plan: result.data,
                                locale: request.locale
                            });
                        } else {
                            response.redirect('/plan?from=console');
                        }
                    });
                }
            ]);
        }
    }

    setup() {
        this.registerVerb(HTTP_VERBS.GET, this.doGET);
    }
}

module.exports = ConsoleHandler;